package com.woniuxy.oldmanapi.intercepters;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.oldmanapi.utils.JwtUtils;
import com.woniuxy.oldmanapi.vo.ResponseResult;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class PermissionInterceper implements HandlerInterceptor {
    @Autowired
    JwtUtils jwtUtils ;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));

        //放行 options请求
        //查看以下  客户请求的资源
        String path = request.getServletPath();
        System.out.println("========="+path+"=========");

        //跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if ("OPTIONS".equals(request.getMethod())){
            response.setStatus(HttpServletResponse.SC_OK);
            return true ;
        }

        //获取token
        String token = request.getHeader("token");
        if (token != null) {
            try {
                //解析没有出问题就好，这个返回值要不要都无所谓，如果随便传进来一个token带进来的话就会报错
                Claims claims = jwtUtils.parseToken(token);
                return true ;
            }catch (Exception e) {
                e.printStackTrace();
            }
        }

        ResponseResult<Void> result = new ResponseResult<>();
        result.setCode(403);
        result.setMsg("没有权限访问，请先登录!");

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(result);
        //往前台返回一个json字符串
        response.getWriter().print(json);
        return false ;
    }
}
